// Custom Router for Claude Code Router
// Implements token-based routing logic for qwen-long model

/**
 * Custom router function that routes requests based on input token count
 * @param {Object} req - The request object from Claude Code
 * @param {Object} config - The configuration object
 * @returns {string|null} - "provider,model" string or null to fall back to default router
 */
async function router(req, config) {
  // Token estimation function (same logic as transformers)
  function estimateTokenCount(text) {
    if (!text || typeof text !== 'string') return 0;
    const englishChars = text.match(/[a-zA-Z0-9\s\.,!?;:\-'"()[\]{}]/g)?.length || 0;
    const otherChars = text.length - englishChars;
    return Math.ceil(englishChars / 4 + otherChars / 1.5);
  }

  // Calculate total input tokens from messages
  function calculateInputTokens(messages) {
    if (!Array.isArray(messages)) return 0;
    
    let totalTokens = 0;
    for (const message of messages) {
      if (message.content) {
        if (typeof message.content === 'string') {
          totalTokens += estimateTokenCount(message.content);
        } else if (Array.isArray(message.content)) {
          for (const content of message.content) {
            if (content.type === 'text' && content.text) {
              totalTokens += estimateTokenCount(content.text);
            } else if (content.type === 'image') {
              totalTokens += 1000;
            }
          }
        }
      }
      if (message.role) {
        totalTokens += 5;
      }
    }
    return totalTokens;
  }

  // Check if request has messages
  if (!req.messages || !Array.isArray(req.messages)) {
    return null; // Fall back to default router
  }

  // Calculate input tokens
  const inputTokens = calculateInputTokens(req.messages);
  const LONG_CONTEXT_THRESHOLD = 20000; // 20k tokens threshold
  
  // Log routing decision
  if (process.env.LOG === 'true' || process.env.LOG === true) {
    console.log(`[CustomRouter] Input tokens: ${inputTokens}, Threshold: ${LONG_CONTEXT_THRESHOLD}`);
  }

  // Route to qwen-long for large contexts (> 8k tokens)
  if (inputTokens > LONG_CONTEXT_THRESHOLD) {
    if (process.env.LOG === 'true' || process.env.LOG === true) {
      console.log(`[CustomRouter] Large context detected (${inputTokens} > ${LONG_CONTEXT_THRESHOLD}). Routing to qwen-long.`);
    }
    return "dashscope,qwen-long";
  }

  // For smaller contexts, fall back to default router rules
  return null;
}

module.exports = router;
